<template>
  <div>
    <el-row :gutter="20">
      <div class="app-container">
        <el-row type="flex" justify="start" align="middle">
          <el-col :span="4"
            ><span class="el-custom-title"
              >工序支线</span
            ></el-col
          >
          <el-col :span="20" style="float:right;">
            <el-button-group style="float: right">
              <el-button
                type="primary"
                icon="el-icon-plus"
                class="el-button--mini"
                @click="handleCreate"
                >添加</el-button
              >
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="handleUpdate()"
              >
                编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="ui_delete(null, null)"
              >
                删除
              </el-button>
              <el-button
                type="primary"
                icon="el-icon-download"
                class="el-button--mini"
                @click="handleImport"
                >导入工序</el-button
              >
            </el-button-group>
          </el-col>
        </el-row>
        <el-row type="flex" justify="start">
          <el-table
            v-loading="listLoading"
            :data="list"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            @row-click="rowClick"
            @selection-change="handleSelectionChange"
            ref="tableMain"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column
              align="center"
              label="支线编号"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.productProcedureBranchNo }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="支线名称"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.productProcedureBranchName }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="备注"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.comment }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="是否主线"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.ismain | resolveEnableValue }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="产品工序id"
              width="95"
              v-if="false"
            >
              <template slot-scope="scope">
                {{ scope.row.productProcedureId }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="产品工序线"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.productProcedureName }}
              </template>
            </el-table-column>
                     <el-table-column
              align="center"
              label="工序数"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.procedureCount }}
              </template>
            </el-table-column>
                     <el-table-column
              align="center"
              label="工艺数量"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.technologyCount }}
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.limit"
            :page-sizes="listQuery.pageSizes"
            @pagination="fetchData"
          />
        </el-row>
      </div>
    </el-row>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="产品支线编号" prop="productProcedureBranchNo">
          <el-input v-model="temp.productProcedureBranchNo" />
        </el-form-item>
        <el-form-item
          label="产品工序支线名称"
          prop="productProcedureBranchName"
        >
          <el-input v-model="temp.productProcedureBranchName" />
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="temp.comment" />
        </el-form-item>
        <el-form-item label="是否主线" prop="ismain">
          <el-select
            v-model="temp.ismain"
            class="filter-item"
            placeholder="请选择"
          >
            <el-option
              v-for="item in this.lstBoolValues"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品工序线" prop="productProcedureId">
          <el-select
            v-model="temp.productProcedureLineId"
            class="filter-item"
            placeholder="请选择产品工序线"
          >
            <el-option
              v-for="item in this.lstProductProcedureIds"
              :key="item.id"
              :label="item.productProcedureName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? ui_create() : ui_update()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>

    <mesprocedureimportchild
      :mesproductprocedurebranchid="
        this.lstSelected != null && this.lstSelected.length > 0
          ? this.lstSelected[0].id
          : 0
      "
      :dialogVisible="this.dialogImportVisible"
      ref="dataImport"
      @childClose="closeChild"
      @refresh="this.fetchData"
    ></mesprocedureimportchild>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import mesprocedureimportchild from "@/views/procedure/product/mesProcedureImportChild";

import {
  getAll,
  getOne,
  getList,
  create,
  update,
  deleteBatch,
  saveRelation,
} from "@/api/procedure/product/mesProductProcedureBranch";

import { getAll as getAllMesProductProcedures } from "@/api/procedure/product/mesProductProcedure";

import ElSelectTree from "el-select-tree";
export default {
  name: "mesproductbranchchild",
  components: { Pagination, ElSelectTree, mesprocedureimportchild },
  data() {
    return {
      data: [],
      list: [],
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      curProcedureBranchId: 0,
      dialogFormVisible: false,
      dialogImportVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建",
        import: "导入"
      },
      rules: {
        productProcedureBranchNo: [
          {
            required: true,
            message: "产品支线编号不能为空！",
            trigger: "change"
          }
        ],
        productProcedureBranchName: [
          {
            required: true,
            message: "产品工序支线名称不能为空！",
            trigger: "change"
          }
        ],
        isMain: [
          {
            required: true,
            message: "是否主线不能为空！",
            trigger: "change"
          }
        ],
        productProcedureLineId: [
          {
            required: true,
            message: "产品工序id不能为空！",
            trigger: "change"
          }
        ]
      },
      temp: {
        id: 0,
        productProcedureBranchNo: "",
        productProcedureBranchName: "",
        comment: "",
        ismain: false,
        productProcedureLineId: 0, //产品工序支线Id
        relationId:0,  //关系表Id
      },
      //表格變量
      lstSelected: [],
      lstProductProcedureIds: [],
      clearable: true,
      defaultExpandAll: true,
      multiple: false,
      placeholder: "请选择",
      disabled: false,
      checkStrictly: true,
      defaultProps: {
        value: "id",
        children: "children",
        label: "procedureSetName"
      },
      lstBoolValues: [
        { value: true, label: "是" },
        { value: false, label: "否" }
      ]
    };
  },
  props: {
    mesprocedurebranchid: {}
  },
  watch: {
    mesprocedurebranchid: function(newVale, oldValue) {
      if (newVale != null) {
        this.curProcedureBranchId = newVale;
      }
    },
    deep: true
  },
  filters: {
    resolveEnableValue(p) {
      return p ? "是" : "否";
    }
  },
  created() {
    this.fetchData();
    this.getAllMesProductProcedureIds();
  },
  methods: {
    handleSelectionChange(val) {
      this.lstSelected = val;
    },
    fetchData() {
      let param = {
        page: this.listQuery.page,
        size: this.listQuery.limit
      };
      this.listLoading = true;
      getList(param).then(response => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.listLoading = false;
        //通知父组件刷新
        this.$emit("refreshSteps", this.list);
      });
    },
    rowClick(row, column, event) {
      this.currentTherbligsTypeId = row.id;
      //this.getTherbligs()
    },
    ui_create() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.temp.id = 0; //自增
          
          saveRelation(this.temp).then(response => {
            this.temp.id = response.data.productProcedureBranchId;
            this.temp.relationId = response.data.id;
            this.temp.productProcedureLineId = response.data.procedureLineId
            this.fetchData()
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "添加成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_update() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          saveRelation(this.temp).then(() => {
           this.fetchData()
           this.dialogFormVisible = false;
            //通知父组件刷新
            //this.$emit("refreshSteps",this.list)
            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_delete(row, index) {
      let selected = this.$refs.tableMain.selection;
      if (selected == null || selected.length == 0) {
        this.$message.error("请先选择工序支线");
        return;
      }
      let ids = [];
      selected.map(function(elm) {
        ids.push(elm.id);
      });

      deleteBatch(ids).then(() => {
        ids.forEach(elm => {
          const index = this.list.findIndex(v => v.id === elm);
          this.list.splice(index, 1);
        });
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000
        });
      });
    },
    resetTemp() {
      this.temp = {
        id: 0,
        productProcedureBranchNo: "",
        productProcedureBranchName: "",
        comment: "",
        ismain: false,
        productProcedureId: 0
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleImport() {
      if (this.lstSelected == 0 || this.lstSelected.length == 0) {
        this.$message.error("请先选择一条工序支线");
        return;
      }
      this.resetTempImport();
      this.dialogStatus = "import";
      this.dialogImportVisible = true;
    },
    handleUpdate() {
      let selected = this.$refs.tableMain.selection;
      if (selected == null || selected.length !== 1) {
        this.$message.error("请先选择一条工序支线");
        return;
      }
      this.temp = Object.assign({}, this.lstSelected[0]); // copy obj
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    resetTempImport() {
      this.tempImport = {
        workSectionId: 0,
        parentId: 0
      };
    },
    ui_query() {
      this.fetchData();
    },

    handleSelectionChangeSon(val) {
      if (val == null || val.length == 0) return;
      let cur = this.list.find(v => v.id == val[0].id);
      if (cur != null) {
        this.tempson = Object.assign({}, cur);
      }
    },
    getAllMesProductProcedureIds() {
      this.lstProductProcedureIds.length = 0;
      this.lstProductProcedureIds.push({
        id: 0,
        productProcedureName: "请选择"
      });
      getAllMesProductProcedures().then(response => {
        let r = response.data.map(itm => {
          return { id: itm.id, productProcedureName: itm.productProcedureName };
        });

        this.lstProductProcedureIds = this.lstProductProcedureIds.concat(r);
      });
    },
    closeChild(val) {
      ;
      this.dialogImportVisible = val;
    }
  }
};
</script>
<style>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
